<template>
<!-- 面包屑导航区域-->
<div class="head">
  <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item>学生信息管理</el-breadcrumb-item>
  </el-breadcrumb>
  <el-input
      class="search1"
      v-model="s_in1"
      style="width: 150px"
      placeholder="搜索专业"
      :suffix-icon="Search"
    />
    <el-input
      class="search2"
      v-model="s_in2"
      style="width: 150px"
      placeholder="搜索班级"
      :suffix-icon="Search"
    />
    <el-input
      class="search3"
      v-model="s_in3"
      style="width: 150px"
      placeholder="搜索学号"
      :suffix-icon="Search"
    />
    <el-button class="search_b" type="primary" @click="search_fun">搜索</el-button>
    <el-button class="init_b" type="success" @click="init_fun">复原</el-button>
</div>

<!--以下是主页面列表-->
<el-card class="card">
        <div class="button_div">
                <el-button type="success" @click="addStudent()" :disabled="b_s" >新增</el-button>
                <el-button type="warning" @click="updateStudent" :disabled="b_s" >修改</el-button>
                <el-button type="danger" @click="deleteStudent" :disabled="b_s" >删除</el-button>
                <span class="span_t">[点击对应条目实现单选]--已选中:</span>
                <span class="span_s">{{ select }}</span>
            </div>
        <el-table  highlight-current-row  @current-change="handleCurrentChange" :data="paginatedData" style="width: 100%">
                <el-table-column type="index" label="序号" width="55" >
<!-- 以下是确保在第二页的时候。序号从11开始-->
                    <template v-slot="scope">
                        <span>
                            {{ (this.currentPage- 1) * this.pageSize + scope.$index + 1 }}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column prop="student_id" label="学生学号" width="150" sortable />
                <el-table-column prop="name" label="姓名" width="120" sortable  />
                <el-table-column prop="gender" label="性别" width="80"/>
                <el-table-column prop="birth_date" label="出生日期" width="150"/>
                <el-table-column prop="grade" label="年级" width="100"/>
                <el-table-column prop="major" label="专业" width="120"/>
                <el-table-column prop="class" label="班级" width="150"/>
            </el-table>
        <!-- 分页栏 -->
        <div class="pagination">
            <el-pagination
                background
                layout="prev, pager, next"
                :total="tableData.length"
                :page-size="pageSize"
                v-model:current-page="currentPage"
                @current-change="handleCurrentChange"/>
        </div>
</el-card>
<!--新增的对话框-->
<el-dialog v-model="Addvisual" title="添加学生信息" width="50%">
  <AddStudent @close-dialog="closeAddForm()" @submit-form="submitAddForm" />
</el-dialog>
<el-dialog v-model="Upvisual" title="修改学生信息" width="50%">
  <UpStudent :current-student="currentRow" @close-dialog="closeUpForm()" @submit-form="submitUpForm" />
</el-dialog>
</template>

<script>
import StudentApi from '@/api/StudentApi';
import AddStudent from './FormWin/AddForm/AddStudent.vue';
import UpStudent from './FormWin/UpdataForm/UpStudent.vue';
import stroe from '../store/index'

export default {
  components:{
    AddStudent,
    UpStudent
  },
  data() {
    return {
      tableData: [],
      select: "未选中",
      currentRow: null,
      pageSize: 10, // 默认每页显示的条数
      currentPage: 1, // 当前页码
      Addvisual:false,//新增表单的显示
      Upvisual:false,//修改表单的
      s_in1:'',
      s_in2:'',
      s_in3:''
    };
  },
  computed: {
    paginatedData() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.tableData.slice(start, end);
    },
    b_s(){ //如果是管理员，按钮可选
      if(stroe.state.userType=='admin'){
        return false;
      }
      return true;
    }
  },
  methods: {
    init_fun(){
      this.Frensh();
      this.s_in1='';
      this.s_in2='';
      this.s_in3='';
      this.$message({
            message: '重载完成',
            type: 'success'
        });
    },
    search_fun(){
      StudentApi.search(this.s_in1,this.s_in2,this.s_in3).then(res => {
        this.tableData = res.data.searchData;
      });
    },
    //刷新操作
    Frensh(){
      StudentApi.getAll().then(res => {
        this.tableData = res.data.tableData;
      });
    },
    handleCurrentChange(val) {
      this.currentRow = val;
      if (val) {
        this.select = `第${this.paginatedData.findIndex(row => row.student_id === val.student_id) + 1}条 - 学号: ${val.student_id}, 姓名: ${val.name}`;
      } else {
        this.select = "未选中";
      }
    },
    addStudent() {
      // 新增学生逻辑
      this.Addvisual=true;
      //显示表单后，后面去表单提交函数执行
    },
    updateStudent() {
      if (!this.currentRow) {
        this.$message({
            message: '请先选择要修改的学生',
            type: 'warning'
        });
        return;
      }
      // 修改学生逻辑
      this.Upvisual=true;
    },
    deleteStudent() {
      // 删除学生逻辑
      if (!this.currentRow) {
        this.$message({
          message: '请先选择要删除的学生',
          type: 'warning'
        });
        return;
      }
      //已经选中了后
      else{
        this.$confirm(`确定要删除学生: ${this.currentRow.student_id} 吗?-[此操作会使得所有相关于该学生的信息被删除]`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {// 用户确认删除
          StudentApi.del_one(this.currentRow.student_id).then(res => {
            if (res.data === 1) {
                this.$message({
                  message: '删除成功',
                  type: 'success'
              });
            }
            this.Frensh();
          })
        }).catch(()=>{
          this.$message({
                message: '取消删除',
                type: 'success'
            });
        })
      }
  },
    //以下是弹出表单相关的处理方法。
    //打开，关闭。
    closeAddForm(){
      this.Addvisual=false;
    },
    closeUpForm(){
      this.Upvisual=false;
    },
    //以下是表单提交等
    submitAddForm(formDate){
      //先要验证，学号是否重复了
      const idExists = this.tableData.some(student => student.student_id === formDate.student_id);
      if (idExists) {
        this.$message({
          message: '学号已存在！',
          type: 'warning'
        });
        this.Addvisual=false;
        return;
      } else {
        //如果学号没重复，合法的，存后端。
        StudentApi.add_one(formDate).then(res=>{
          if(res.data==1){
            this.$message({
              message:'添加学生成功！',
              type:'success'
            })
            this.Addvisual=false;
            //如果成功，刷新页面
            this.Frensh();
          }
          else{
            this.$message({
              message:'添加学生失败！',
              type:'error'
            })
            this.Addvisual=false;
          }
        })
        
      }
    },
    //修改
    submitUpForm(formDate){
      this.$confirm(`确定要修改学生${this.currentRow.student_id} 吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {// 用户确认修改
          StudentApi.updata_one(formDate).then(res => {
            if (res.data === 1) {
                this.$message({
                  message: '修改成功',
                  type: 'success'
              });
            }
            this.Upvisual=false;
            this.Frensh();
          })
        }).catch(()=>{
          this.$message({
                message: '取消修改',
                type: 'success'
            });
        })
    },
    handleResize() {
      // 检查窗口高度并调整pageSize
      const  win_height=window.innerHeight;
      if(win_height <= 750){
        this.pageSize = 10;
      }
      else if (win_height > 750 && win_height <=800) {
        this.pageSize = 11;
      }
      else if(win_height > 800 &&  win_height<=850){
        this.pageSize = 12;
      }
      else if(win_height > 850 && win_height <=900){
        this.pageSize = 13;
      }
      else if(win_height > 900 && win_height <=950){
        this.pageSize = 14;
      }
      else if(win_height > 950) {
        this.pageSize = 15;
      }
    },
  },
  created() {
    StudentApi.getAll().then(res => {
      this.tableData = res.data.tableData;
    });
  },
  mounted() {
    this.handleResize();
    window.addEventListener('resize', this.handleResize);
  },
  beforeUnmount() {
    window.removeEventListener('resize', this.handleResize);
  }
};
</script>

<style lang="css" src="../styles/Studentmain.css" scoped ></style>
